/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sg.edu.nus.iss.pacman.net.sms.client;

import java.io.IOException;
import javax.microedition.io.Connector;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;

/**
 * This class is used for sending SMS.
 * @author fredy
 */
public class SMSClient
{
    private static final String SMS_PROTOCOL = "sms://";
    private SMSClientListener listener;

    /**
     * Creates a new instance of SMSClient.
     * @param listener the SMSClientListener
     */
    public SMSClient(SMSClientListener listener)
    {
        this.listener = listener;
    }

    /**
     * Sends the SMS. This method doesn't block.
     * @param phoneNumber the phone number.
     * @param sms the SMS
     */
    public void sendSMS(String phoneNumber, String sms)
    {
        Thread t = new Thread(new SMSClientRunnable(phoneNumber, sms));
        t.start();
    }

    class SMSClientRunnable implements Runnable
    {
        private String phoneNumber;
        private String sms;

        public SMSClientRunnable(String phoneNumber, String sms)
        {
            this.phoneNumber = phoneNumber;
            this.sms = sms;
        }
        
        public void run()
        {
            send();
            listener.sent();
        }

        private void send()
        {
            MessageConnection conn = null;
            try
            {
                conn = (MessageConnection) Connector.open(SMS_PROTOCOL + phoneNumber);
                TextMessage msg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
                msg.setPayloadText(sms);
                conn.send(msg);
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
                throw new RuntimeException(ex.getMessage());
            }
            finally
            {
                if (conn != null)
                {
                    try
                    {
                        conn.close();
                    }
                    catch (IOException ex)
                    {
                        ex.printStackTrace();
                        throw new RuntimeException(ex.getMessage());
                    }
                }
            }
        }
    }
}
